"""
2018.10.27
以最简洁的方式完成一个搜索，用户可以实现自己的功能_do()。
"""
class Search:
    import os,re
    sum = 0

    def __init__(self, path, file, txt):
        self.path = path
        self.file = file
        self.txt = txt

    def search(self):
        self._dir(self.path)

    def _dir(self, path):
        """
        递归目录，处理每个子目录。
        :param path:
        :return:
        """
        if self.os.path.isdir(path):
            paths = self._getdirs(path)

            for p in paths:
                temp = self._combine(path, p)
                if Search.os.path.isdir(temp):
                    self._dir(temp)
                elif Search.os.path.isfile(temp):
                    self._file(temp)
        elif Search.os.path.isfile(self.path):
            self._file(self.path)

    def _file(self, path):
        """
        找到特定的文件进行处理。
        """
        if path.endswith(self.file):
            Search.sum += 1
            # print("count %3s , file %s : " % (Search.sum, path))
            self._do(path)

        # i = 0
        # numbers = 0     # 行数。
        # lines = 1       # 显示搜索指定内容行后几行。
        # try:  # 遇到iso-8859会报错。
        #     for f in open(path):
        #         m = Search.re.match(self.txt, f)
        #         # if self.txt in f or i > 0:
        #         if m or i > 0:          # 使用正则表达式进行判断。
        #             i = lines if i == 0 else i
        #             i -= 1
        #             numbers += 1
        #             print(numbers, " : ", i, " : ", f)
        #     if numbers > 0:
        #         print("-" * 30)
        #         print("_file : ", path)
        # except:
        #     # print("*" * 30)
        #     # print(path)
        #     pass
        pass

    def _do(self, path):
        """
        用户实现的代码。
        """
        try:
            for t in open(path):
                if self.txt in t:
                    print("file : ", path)
                    print(t)
        except:
            pass
        pass

    def _combine(self, path, sub):
        """
        主目录和子目录合并。
        """
        return path + '/' + sub

    def _getdirs(self, path):
        """
        获取目录下的所有文件。
        """
        if Search.os.path.isdir(path):
            return Search.os.listdir(path)
        elif Search.os.path.isfile(path):
            return path


if __name__ == '__main__':
    args = ['sdfs', '-a','.py','-d', 'a,f,sf,,']
    s = Search("/usr/include", ".h", "char ")
    s.search()